﻿using CN.T.Backend.Application.System.Utility;
using DRNetCore.Api.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;

namespace CN.T.Backend.Application.System.Services
{
    public class TPlusService : ITPlusService, ITransient
    {
        public  List<KeyValuePair<string, string>> _key;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISession _session;
        private readonly IMemoryCache _memoryCachedal;
        public TPlusService(IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache) {
            _httpContextAccessor = httpContextAccessor;
             _session = _httpContextAccessor.HttpContext.Session;
            _memoryCachedal = memoryCache;
        }
        //回调函数变量
        //TPulsMsg encryptMsgb =new TPulsMsg();
        //MessageBase Msg_Pay = new MessageBase();
        //MessageBase Msg_TempAuth = new MessageBase();
        //MessageBase Msg_Ticket =new MessageBase();
        //MessageBase Msg_Test = new MessageBase();
        /// <summary>
        /// 接口回调方法
        /// </summary>
        /// <param name="encryptMsg">回调密文信息</param>
        /// <returns></returns>
        public async Task<Tuple<bool, string, object?>> Receive(TPulsMsg encryptMsg)
        {
            try
            {
                //存入密文信息
                _memoryCachedal.Set("Errmsg", encryptMsg);
                string enMsg = encryptMsg.encryptMsg;

                //Console.WriteLine($"解密前的消息{enMsg}"); 解密信息
                string decryptMsg = OpenapiHelp.AesDecrypt(enMsg, "6B0EC6C042B9A684");//
                //Console.WriteLine($"解密后消息{decryptMsg}");

                MessageBase message = JsonConvert.DeserializeObject<MessageBase>(decryptMsg);
                object retObj = null;
                try
                {
                    switch (message.msgType)
                    {
                        case "APP_TEST":
                            retObj = DealTestMsg(message);
                            break;
                        case "APP_TICKET"://获取应用凭证返回
                            retObj = DealTicketMsg(message);
                            break;
                        case "TEMP_AUTH_CODE"://触发企业临时授权码推送
                            retObj = DealOrgTempAuthMsg(message);
                            break;
                        case "PAY_ORDER_SUCCESS":
                            retObj = DealOrderPayMsg(message);
                            break;
                        default:
                            break;
                    }
                    return new(true, "请求成功", retObj);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                return new(false, "请求失败" + ex.Message, null);
            }
        }

        private object DealOrderPayMsg(MessageBase message)
        {
            OrderPayContent content = JsonConvert.DeserializeObject<OrderPayContent>(message.bizContent.ToString());
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                { "orderNo",$"{content.orderNo}"},
                { "orgId",$"{content.orgId}"}
            };
            _memoryCachedal.Set("Msg_Pay", message);
            return dic;
        }
        /// <summary>
        /// 触发企业临时授权码推送
        /// </summary>
        /// <param name="message"> 解密后参数</param>
        /// <returns></returns>
        private object? DealOrgTempAuthMsg(MessageBase message)
        {
            OrgTempAuthContent content = JsonConvert.DeserializeObject<OrgTempAuthContent>(message.bizContent.ToString());

            _memoryCachedal.Set("Msg_TempAuth",JsonConvert.SerializeObject(message));
            return $"OrgTempAuthCode:{content.tempAuthCode}";
        }
        /// <summary>
        /// 获取应用凭证返回 APP_TICKET
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private object DealTicketMsg(MessageBase message)
        {
            AppTicketContent content = JsonConvert.DeserializeObject<AppTicketContent>(message.bizContent.ToString());
            var json = JsonConvert.SerializeObject(message);
            _memoryCachedal.Set("Msg_Ticket", message);
            return $"AppTicket:{content.appTicket}";
        }

        private object DealTestMsg(MessageBase message)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                { "result","success"}
            };
            _memoryCachedal.Set("Msg_Test", message);
            return dic;
        }
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool IsExist(string key)
        {
            var value = _memoryCachedal.Get(key);
            return value == null ? false : true;
        }
        /// <summary>
        /// 第一次获取永久token
        /// </summary>
        /// <param name="code">授权后返回的code编码</param>
        /// <returns></returns>
        public async Task<Tuple<bool, string, dynamic?>> GetFristTokenAsync(string code)
        {
            try
            {
                var header1 = new List<KeyValuePair<string, string>>();
                header1.Add(new KeyValuePair<string, string>("appKey", App.Configuration["T+:appKey"]));
                header1.Add(new KeyValuePair<string, string>("appSecret", App.Configuration["T+:appSecret"]));
                //获取user_auth_permanent_code
                var OAuth = "https://www.baidu.com";
                var lssqmurl = $"https://openapi.chanjet.com/auth/v2/getToken?grantType=authorization_code&redirectUri={OAuth}&code={code}";
                var getcode = NetHttpHelp.GetQueryToEntity<FirstTokenDto>(lssqmurl, header1);
                if (getcode.code != "200")
                {
                    return new(false, "token获取失败！", null);
                }

                //await _redis.SetAsync("user_auth_permanent_code", getcode.result.user_auth_permanent_code);改session
                _memoryCachedal.Set("user_auth_permanent_code", getcode.result.user_auth_permanent_code);
                // _httpContextAccessor
                //立即发送消息
                var yypzurl = "https://openapi.chanjet.com/auth/appTicket/resend";
                var fsxx = NetHttpHelp.PostJsonToEntity<LjcsOutDto>(yypzurl, "", header1);
                var appTicket = "";// new MessageBase();
                //获取appTicket
                if (fsxx.code != "200")
                    return new(false, "立即发送appTicket失败！", null);
                Thread.Sleep(1000);
                // var a = _memoryCachedal.Get("1");
                var flag = IsExist("Msg_Ticket");
                if (!flag)
                {
                    Thread.Sleep(1000);
                    var flag1 = IsExist("Msg_Ticket");
                    if (!flag1)
                    {
                        return new(false, "网络异常1", null);
                    }
                        
                    appTicket = JsonConvert.SerializeObject(_memoryCachedal.Get("Msg_Ticket"));// _session.GetString("Msg_Ticket");
                }
                appTicket = JsonConvert.SerializeObject(_memoryCachedal.Get("Msg_Ticket"));// _session.GetString("Msg_Ticket");
                var appTicketMsg = JsonConvert.DeserializeObject<AppTicketMsg>(appTicket);
                appTicket = appTicketMsg.bizContent.appTicket;
                //获取应用凭证
                if (appTicket.Length < 1)
                    return new(false, "appTicket获取失败！", null);
                var hqyyindto = new HqyyInDto();
                hqyyindto.appTicket = appTicket;
                var tempAuthCode = "";
                header1.Add(new KeyValuePair<string, string>("Content-Type", "application/json"));
                var yypzurls = "https://openapi.chanjet.com/auth/appAuth/getAppAccessToken";
                var hqyypzstr = NetHttpHelp.PostJsonToString(yypzurls, JsonConvert.SerializeObject(hqyyindto), header1);
                ///// var hqyypz = NetHttpHelp.PostEntityToEntity<HqyyInDto, HqyyOutDto> (AppConfig.GetSection("TPlus:Url_Server_SX").Get<string>() + AppConfig.GetSection("TPlus:Url_getAppAccessToken").Get<string>(),hqyyindto, header1);
                var hqyypz = JsonConvert.DeserializeObject<HqyyOutDto>(hqyypzstr);
                if (hqyypz.code != "200")
                    return new(false, $"获取应用凭证接口失败！请求网址：{yypzurls}返回信息：{hqyypzstr},使用的appTicket{appTicket}", null);
                Thread.Sleep(1000);
                var flagTemp =  IsExist("Msg_TempAuth");
                if (!flagTemp)
                {
                    Thread.Sleep(2000);
                    var flag1 =  IsExist("Msg_TempAuth");
                    if (!flag1)
                    {
                        //重新调用接口获取企业临时码
                        await Qylssqm();
                        Thread.Sleep(4000);
                        var flag2 = IsExist("Msg_TempAuth");
                        if (!flag2)
                        {
                            return new(false, "网络异常2", null);
                        }
                         
                    }
                    tempAuthCode = _memoryCachedal.Get("Msg_TempAuth").ToString();
                }
                tempAuthCode = _memoryCachedal.Get("Msg_TempAuth").ToString();
                var tempAuthCodeMsg = JsonConvert.DeserializeObject<OrgTempAuthContentMsg>(tempAuthCode);
                tempAuthCode = tempAuthCodeMsg.bizContent.tempAuthCode;
                if (tempAuthCode.Length < 1)
                    return new(false, "获取应用凭证Msg_TempAuth失败！", null);
                //获取企业永久授权码
                var hqyyjsqmurl = "https://openapi.chanjet.com/auth/orgAuth/getPermanentAuthCode";
                var hqqyyjsqm = new HqqyyjsqmInDto();
                hqqyyjsqm.appAccessToken = hqyypz.result.appAccessToken;
                hqqyyjsqm.tempAuthCode = tempAuthCode;
                var hqhyyjsqm = NetHttpHelp.PostEntityToEntity<HqqyyjsqmInDto, HqqyyjsqmOutDto>(hqyyjsqmurl, hqqyyjsqm, header1);
                if (hqhyyjsqm.code != "200")
                    return new(false, "获取企业永久授权码接口失败！", null);
                _memoryCachedal.Set("permanentAuthCode", hqhyyjsqm.result.permanentAuthCode.ToString());
                //获取企业凭证
                var hqqypzurl = "https://openapi.chanjet.com/auth/orgAuth/getOrgAccessToken";
                var hqqypzin = new HqqypzInDto();
                hqqypzin.appAccessToken = hqyypz.result.appAccessToken;
                hqqypzin.permanentAuthCode = hqhyyjsqm.result.permanentAuthCode;
                var hqqypzout = NetHttpHelp.PostEntityToEntity<HqqypzInDto, HqqypzOutDto>(hqqypzurl, hqqypzin, header1);
                if (hqqypzout.code != "200")
                    return new(false, "获取企业凭证接口失败！", null);
                var hqyjtoken = new HqyjstokenInDto();
                hqyjtoken.userAuthPermanentCode = getcode.result.user_auth_permanent_code;
                hqyjtoken.orgAccessToken = hqqypzout.result.orgAccessToken;
                var hqyjtokenurl = "https://openapi.chanjet.com/auth/token/getTokenByPermanentCode";
                var hqyjtokenout = NetHttpHelp.PostEntityToEntity<HqyjstokenInDto, HqyjstokenOutDto>(hqyjtokenurl, hqyjtoken, header1);
                return new(true, "请求成功", hqyjtokenout.result.access_token);//hqyjtokenout.result.access_token
            }
            catch (Exception ex)
            {
                return new(false, "请求失败" + ex.Message, null);
            }
        }
        /// <summary>
        /// 第一次授权成功后，无需在获取code 刷新token
        /// </summary>
        /// <returns></returns>
        public async Task<Tuple<bool, string, dynamic?>> PermanentTokenAsync()
        {
            
            var user_auth_permanent_code =  _memoryCachedal.Get("user_auth_permanent_code").ToString();
            var header1 = new List<KeyValuePair<string, string>>();
            header1.Add(new KeyValuePair<string, string>("appKey", App.Configuration["T+:appKey"]));
            header1.Add(new KeyValuePair<string, string>("appSecret", App.Configuration["T+:appSecret"]));
            header1.Add(new KeyValuePair<string, string>("Content-Type", "application/json"));
            ///立即发送消息
            var yypzurl = "https://openapi.chanjet.com/auth/appTicket/resend";
            var fsxx = NetHttpHelp.PostJsonToEntity<LjcsOutDto>(yypzurl, "", header1);
            var appTicket = "";
            //获取appTicket
            if (fsxx.code != "200")
                return new(false, "立即获取appTick错误", null);
            Thread.Sleep(1000);
            var flag = IsExist("Msg_Ticket");
            if (!flag)
            {
                Thread.Sleep(2000);
                var flag1 = IsExist("Msg_Ticket");
                if (!flag1)
                    return new(false, "网络异常", null);
            }
            appTicket = JsonConvert.SerializeObject(_memoryCachedal.Get("Msg_Ticket")).ToString();
            var appTicketMsg = JsonConvert.DeserializeObject<AppTicketMsg>(appTicket);
            appTicket = appTicketMsg.bizContent.appTicket;
            if (appTicket.Length < 1)
                return new(false, "appTick错误！", null);
            //获取应用凭证
            var hqyyindto = new HqyyInDto();
            hqyyindto.appTicket = appTicket;
            var permanentAuthCode =  _memoryCachedal.Get("permanentAuthCode").ToString();
            var hqyypz = NetHttpHelp.PostEntityToEntity<HqyyInDto, HqyyOutDto>(" https://openapi.chanjet.com/auth/appAuth/getAppAccessToken", hqyyindto, header1);
            if (hqyypz.code != "200")
                return new(false, "获取应用凭证失败！", null);
            var hqqypzurl = "https://openapi.chanjet.com/auth/orgAuth/getOrgAccessToken";
            var hqqypzin = new HqqypzInDto();
            hqqypzin.appAccessToken = hqyypz.result.appAccessToken;
            hqqypzin.permanentAuthCode = permanentAuthCode;
            var hqqypzout = NetHttpHelp.PostEntityToEntity<HqqypzInDto, HqqypzOutDto>(hqqypzurl, hqqypzin, header1);
            if (hqqypzout.code != "200")
                return new(false, "获取企业凭证失败!", null);
            var hqyjtoken = new HqyjstokenInDto();
            hqyjtoken.userAuthPermanentCode = user_auth_permanent_code;
            hqyjtoken.orgAccessToken = hqqypzout.result.orgAccessToken;
            var hqyjtokenurl = "https://openapi.chanjet.com/auth/token/getTokenByPermanentCode";
            var hqyjtokenout = NetHttpHelp.PostEntityToEntity<HqyjstokenInDto, HqyjstokenOutDto>(hqyjtokenurl, hqyjtoken, header1);
            _memoryCachedal.Set("OpenToken", hqyjtokenout.result.access_token);
            return new(true, "请求成功", hqyjtokenout.result.access_token);
        }
        /// <summary>
        /// 重新调用接口获取企业临时码
        /// 第一次授权回调的临时码，
        /// 触发企业临时授权码推送
        /// </summary>
        /// <returns></returns>
        public async Task<Tuple<bool, string, dynamic>> Qylssqm()
        {
            var header1 = new List<KeyValuePair<string, string>>();
            //header1.Add(new KeyValuePair<string, string>("appKey", "RQkXCPlI"));
            header1.Add(new KeyValuePair<string, string>("appKey", App.Configuration["T+:appKey"]));
            header1.Add(new KeyValuePair<string, string>("appSecret", App.Configuration["T+:appSecret"]));
           // header1.Add(new KeyValuePair<string, string>("appSecret", "5E282943CC31F1963E61CB0300A40BDC"));
            var qylssqm = "https://openapi.chanjet.com/auth/orgTempAuthCode/resend?orgId=1235851544319882&appName=tpluscloud";
            var getcode = NetHttpHelp.GetQueryToEntity<object>(qylssqm, header1);
            //var a= await Receive(getcode)==null;
            return new (true, "", getcode); 
        }
    }
}
